package com.bayi.storage.utils;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by guoping on 16/5/31.
 */
public class StringUtil {


    /**
     * 加密     * oldWord：需要加密的文字/比如密码
     */
    public static String setEncryption(String oldWord) {
        try {
            String encodeWord = "";
            if (encodeWord != null) {
                encodeWord = Base64.encodeToString(oldWord.getBytes("utf-8"), Base64.NO_WRAP);
            }
            return encodeWord;
//            Log.i("Tag", " encode wrods = " + encodeWord);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 手机号用****号隐藏中间数字
     *
     * @param phone
     * @return
     */
    public static String settingPhone(String phone) {
        String phone_s = "";
        if (!StringUtil.isEmpty(phone)) {
            phone_s = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        }
        return phone_s;
    }

    /**
     * 解密* encodeWord：加密后的文字/比如密码
     */
    public static String setDecrypt(String encodeWord) {
        try {
            String decodeWord = "";
            if (encodeWord != null) {
                decodeWord = new String(Base64.decode(encodeWord, Base64.NO_WRAP), "utf-8");
            }

            Log.i("Tag", "decode wrods = " + decodeWord);
            return decodeWord;

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }


    public static boolean isNumber(String str) {
        if (str == null) {
            return false;
        }
        return str.matches("^\\d+?(\\.\\d+)?$");
    }

    public static boolean isPhone(String phone) {
//        String telRegex = "^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))\\d{8}$";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        String telRegex = "^1\\d{10}$";// "[1]"有10位。
        if (TextUtils.isEmpty(phone))
            return false;
        else
            return phone.matches(telRegex);
    }

    public static boolean isBankAccount(String bankAccount) {
        if (isEmpty(bankAccount)) {
            return false;
        }
        bankAccount = bankAccount.replace(" ", "");
        return bankAccount.matches("^(\\d{15,16}|\\d{19})$");
    }

    public static boolean isEmpty(String str) {
        if (str == null || str.equals("null")) {
            return true;
        }
        return TextUtils.isEmpty(str.trim());
    }

    public static String padLeft(String source, int len, char c) {
        while (source.length() < len) {
            source = c + source;
        }
        return source;
    }

    public static String padRight(String source, int len, char c) {
        while (source.length() < len) {
            source = source + c;
        }
        return source;
    }

    public static Integer getNumber(String str) {
        if (str == null) {
            return null;
        }
        Integer number = null;
        Pattern pattern = Pattern.compile("(\\d+)");
        Matcher matcher = pattern.matcher(str);
        if (matcher.find()) {
            number = Integer.parseInt(matcher.group(1));
        }
        return number;
    }

    public static int getLength(String value) {
        int valueLength = 0;
        String chinese = "[\u4e00-\u9fa5]";
        for (int i = 0; i < value.length(); i++) {
            String temp = value.substring(i, i + 1);
            if (temp.matches(chinese)) {
                valueLength += 2;
            } else {
                valueLength += 1;
            }
        }
        return valueLength;
    }

    public static int getStrLength(String value) {
        double valueLength = 0;
        String chinese = "[\u4e00-\u9fa5]";
        for (int i = 0; i < value.length(); i++) {
            String temp = value.substring(i, i + 1);
            if (temp.matches(chinese)) {
                valueLength += 1;
            } else {
                valueLength += 0.5;
            }
        }
        return (int) Math.ceil(valueLength);
    }

    public static String subStringByChAndEn(String value, float width) {
        float rowWidth = width;
        String returnStr = "";
        String chinese = "[\u4e00-\u9fa5]";
        int valueLength = 0;
        for (int i = 0; i < value.length(); i++) {
            String temp = value.substring(i, i + 1);
            if (temp.matches(chinese)) {
                valueLength += 1;
                rowWidth -= 1;
            } else {
                rowWidth -= 0.5;
                valueLength += 1;
            }
            if (rowWidth == 0 || rowWidth == 0.5) {

                if (valueLength >= value.length()) {
                    returnStr = value.substring(0, valueLength);
                } else {
                    returnStr = value.substring(0, valueLength + 1);
                    if (getLength(returnStr) > width * 2) {
                        returnStr = value.substring(0, valueLength);
                    }
                }

                break;
            } else if (i == value.length() - 1) {
                returnStr = value.substring(0, value.length());
            }
        }
        return returnStr;
    }

    public static boolean isSpecial(String str) {
        String limitEx = "[`~!@$%^&*()+=|{}':;',\\[\\].<>/?~！@①￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern pattern = Pattern.compile(limitEx);
        Matcher m = pattern.matcher(str);


        boolean hasEmoji = false;
        for (int i = 0; i < str.length(); i++) {
            char codePoint = str.charAt(i);
            if (getIsEmoji(codePoint)) {
                hasEmoji = true;
                continue;
            }
        }


        if (m.find() || hasEmoji) {
            return true;
        }
        return false;
    }

    public static boolean getIsEmoji(char codePoint) {
        if ((codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA)
                || (codePoint == 0xD)
                || ((codePoint >= 0x20) && (codePoint <= 0xD7FF))
                || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD))
                || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF)))
            return false;
        return true;
    }

    /**
     * 实现文本复制功能
     *
     * @param content
     */
    public static void copy(String content, Context context, String toast) {
        //获取剪贴板管理器：
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText("Label", content);
        // 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);
        ToastUtil.show(toast);
    }


    /**
     * List转数组
     *
     * @param map
     * @return
     */
    public static String[] testMap2Arr(Map<String, String> map) {
        // 将Map Key 转化为List
        List mapKeyList = new ArrayList(map.keySet());
        System.out.println("mapKeyList:" + mapKeyList);
        // 将Map Key 转化为List
        List<String> mapValuesList = new ArrayList(map.values());
        String[] arr = new String[mapValuesList.size()];
        mapValuesList.toArray(arr);//将转化后的数组放入已经创建好的对象中
        return arr;
    }

    /**
     * List转数组
     *
     * @param qosList
     * @return
     */
    public static int[] testList2Arr(List<Integer> qosList) {
        int[] res = new int[qosList.size()];
        int i = 0;
        for (Integer num : qosList) {
            res[i++] = num;
        }
        return res;
    }
}
